	
	-------------------- LAP PHIEU THU TIEN GHI DANH V1.0 -------------------------------------------------
	
	DECLARE @KhoaNhanVienThuTien bigint, @KhoaPhieuGhiDanh bigint, 
	        @SoTienHocChinhThuc numeric(20,4) , @SoTienHocNgoaiGio numeric(20,4), @TongSoTienHoc numeric(20,4), 
	        @KhoaHoc bigint, @HangXe bigint, @LoaiGio int, @DoiTuongGhiDanh bigint
	        
	SET @KhoaNhanVienThuTien = 2
	SET @KhoaPhieuGhiDanh = 1
	
	SELECT @KhoaHoc = KhoaHoc, @HangXe = HangXe, @LoaiGio = HocNgoaiGio, @DoiTuongGhiDanh = DoiTuongGhiDanh
	FROM PhieuGhiDanh 
	WHERE Khoa = @KhoaPhieuGhiDanh
	
	SELECT @SoTienHocChinhThuc = Gia
	FROM BangGia
	WHERE KhoaHoc = @KhoaHoc AND HangXe = @HangXe AND LoaiGio = 0
	
	IF @LoaiGio = 1
		BEGIN
			SELECT @SoTienHocNgoaiGio = Gia
			FROM BangGia
			WHERE KhoaHoc = @KhoaHoc AND HangXe = @HangXe AND LoaiGio = 1
		END

	UPDATE PhieuGhiDanh 
	SET TrangThaiPhieuGhiDanh = 3, KhoaNhanVienThuTien = @KhoaNhanVienThuTien, 
	    SoTienHocChinhThuc = @SoTienHocChinhThuc, SoTienHocNgoaiGio = @SoTienHocNgoaiGio,
	    TongSoTienHoc = @SoTienHocChinhThuc + @SoTienHocNgoaiGio
	WHERE Khoa = @KhoaPhieuGhiDanh
	
	IF NOT EXISTS(
			SELECT *
			FROM DoanhThuGhiDanh
			WHERE KhoaHoc = @KhoaHoc AND HangXe = @HangXe AND DoiTuongGhiDanh = @DoiTuongGhiDanh
		)
		BEGIN
		
			INSERT INTO DoanhThuGhiDanh (KhoaHoc, HangXe, DoiTuongGhiDanh, SoTienHocChinhThuc, SoTienHocNgoaiGio)
			VALUES (@KhoaHoc, @HangXe, @DoiTuongGhiDanh, @SoTienHocChinhThuc, @SoTienHocNgoaiGio)
		
		END
	ELSE
		BEGIN
			
			UPDATE DoanhThuGhiDanh
			SET SoTienHocChinhThuc = @SoTienHocChinhThuc, SoTienHocNgoaiGio = @SoTienHocNgoaiGio
			WHERE KhoaHoc = @KhoaHoc AND HangXe = @HangXe AND DoiTuongGhiDanh = @DoiTuongGhiDanh
		
		END